5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @defgroup JobQueue JobQueue
23 use MediaWiki\MediaWikiServices
;
26 * Class to handle enqueueing and running of background jobs
31 abstract class JobQueue
{
32 /** @var string Wiki ID */
34 /** @var string Job type */
36 /** @var string Job priority for pop() */
38 /** @var int Time to live in seconds */
40 /** @var int Maximum number of times to try a job */
42 /** @var string|bool Read only rationale (or false if r/w) */
43 protected $readOnlyReason;
47 /** @var JobQueueAggregator */
50 const QOS_ATOMIC
= 1; // integer; "all-or-nothing" job insertions
52 const ROOTJOB_TTL
= 2419200; // integer; seconds to remember root jobs (28 days)
55 * @param array $params
58 protected function __construct( array $params ) {
59 $this->domain
= $params['domain'] ??
$params['wiki']; // b/c
60 $this->type
= $params['type'];
61 $this->claimTTL
= $params['claimTTL'] ??
0;
62 $this->maxTries
= $params['maxTries'] ??
3;
63 if ( isset( $params['order'] ) && $params['order'] !== 'any' ) {
64 $this->order
= $params['order'];
66 $this->order
= $this->optimalOrder();
68 if ( !in_array( $this->order
, $this->supportedOrders() ) ) {
69 throw new MWException( __CLASS__
. " does not support '{$this->order}' order." );
71 $this->dupCache
= wfGetCache( CACHE_ANYTHING
);
72 $this->aggr
= $params['aggregator'] ??
new JobQueueAggregatorNull( [] );
73 $this->readOnlyReason
= $params['readOnlyReason'] ??
false;
77 * Get a job queue object of the specified type.
79 * - class : What job class to use (determines job type)
80 * - wiki : wiki ID of the wiki the jobs are for (defaults to current wiki)
81 * - type : The name of the job types this queue handles
82 * - order : Order that pop() selects jobs, one of "fifo", "timestamp" or "random".
83 * If "fifo" is used, the queue will effectively be FIFO. Note that job
84 * completion will not appear to be exactly FIFO if there are multiple
85 * job runners since jobs can take different times to finish once popped.
86 * If "timestamp" is used, the queue will at least be loosely ordered
87 * by timestamp, allowing for some jobs to be popped off out of order.
88 * If "random" is used, pop() will pick jobs in random order.
89 * Note that it may only be weakly random (e.g. a lottery of the oldest X).
90 * If "any" is choosen, the queue will use whatever order is the fastest.
91 * This might be useful for improving concurrency for job acquisition.
92 * - claimTTL : If supported, the queue will recycle jobs that have been popped
93 * but not acknowledged as completed after this many seconds. Recycling
94 * of jobs simply means re-inserting them into the queue. Jobs can be
95 * attempted up to three times before being discarded.
96 * - readOnlyReason : Set this to a string to make the queue read-only.
98 * Queue classes should throw an exception if they do not support the options given.
100 * @param array $params
102 * @throws MWException
104 final public static function factory( array $params ) {
105 $class = $params['class'];
106 if ( !class_exists( $class ) ) {
107 throw new MWException( "Invalid job queue class '$class'." );
109 $obj = new $class( $params );
110 if ( !( $obj instanceof self
) ) {
111 throw new MWException( "Class '$class' is not a " . __CLASS__
. " class." );
118 * @return string Wiki ID
120 final public function getDomain() {
121 return $this->domain
;
125 * @return string Wiki ID
128 final public function getWiki() {
129 return $this->domain
;
133 * @return string Job type that this queue handles
135 final public function getType() {
140 * @return string One of (random, timestamp, fifo, undefined)
142 final public function getOrder() {
147 * Get the allowed queue orders for configuration validation
149 * @return array Subset of (random, timestamp, fifo, undefined)
151 abstract protected function supportedOrders();
154 * Get the default queue order to use if configuration does not specify one
156 * @return string One of (random, timestamp, fifo, undefined)
158 abstract protected function optimalOrder();
161 * Find out if delayed jobs are supported for configuration validation
163 * @return bool Whether delayed jobs are supported
165 protected function supportsDelayedJobs() {
166 return false; // not implemented
170 * @return bool Whether delayed jobs are enabled
173 final public function delayedJobsEnabled() {
174 return $this->supportsDelayedJobs();
178 * @return string|bool Read-only rational or false if r/w
181 public function getReadOnlyReason() {
182 return $this->readOnlyReason
;
186 * Quickly check if the queue has no available (unacquired, non-delayed) jobs.
187 * Queue classes should use caching if they are any slower without memcached.
189 * If caching is used, this might return false when there are actually no jobs.
190 * If pop() is called and returns false then it should correct the cache. Also,
191 * calling flushCaches() first prevents this. However, this affect is typically
192 * not distinguishable from the race condition between isEmpty() and pop().
195 * @throws JobQueueError
197 final public function isEmpty() {
198 $res = $this->doIsEmpty();
204 * @see JobQueue::isEmpty()
207 abstract protected function doIsEmpty();
210 * Get the number of available (unacquired, non-delayed) jobs in the queue.
211 * Queue classes should use caching if they are any slower without memcached.
213 * If caching is used, this number might be out of date for a minute.
216 * @throws JobQueueError
218 final public function getSize() {
219 $res = $this->doGetSize();
225 * @see JobQueue::getSize()
228 abstract protected function doGetSize();
231 * Get the number of acquired jobs (these are temporarily out of the queue).
232 * Queue classes should use caching if they are any slower without memcached.
234 * If caching is used, this number might be out of date for a minute.
237 * @throws JobQueueError
239 final public function getAcquiredCount() {
240 $res = $this->doGetAcquiredCount();
246 * @see JobQueue::getAcquiredCount()
249 abstract protected function doGetAcquiredCount();
252 * Get the number of delayed jobs (these are temporarily out of the queue).
253 * Queue classes should use caching if they are any slower without memcached.
255 * If caching is used, this number might be out of date for a minute.
258 * @throws JobQueueError
261 final public function getDelayedCount() {
262 $res = $this->doGetDelayedCount();
268 * @see JobQueue::getDelayedCount()
271 protected function doGetDelayedCount() {
272 return 0; // not implemented
276 * Get the number of acquired jobs that can no longer be attempted.
277 * Queue classes should use caching if they are any slower without memcached.
279 * If caching is used, this number might be out of date for a minute.
282 * @throws JobQueueError
284 final public function getAbandonedCount() {
285 $res = $this->doGetAbandonedCount();
291 * @see JobQueue::getAbandonedCount()
294 protected function doGetAbandonedCount() {
295 return 0; // not implemented
299 * Push one or more jobs into the queue.
300 * This does not require $wgJobClasses to be set for the given job type.
301 * Outside callers should use JobQueueGroup::push() instead of this function.
303 * @param IJobSpecification|IJobSpecification[] $jobs
304 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
306 * @throws JobQueueError
308 final public function push( $jobs, $flags = 0 ) {
309 $jobs = is_array( $jobs ) ?
$jobs : [ $jobs ];
310 $this->batchPush( $jobs, $flags );
314 * Push a batch of jobs into the queue.
315 * This does not require $wgJobClasses to be set for the given job type.
316 * Outside callers should use JobQueueGroup::push() instead of this function.
318 * @param IJobSpecification[] $jobs
319 * @param int $flags Bitfield (supports JobQueue::QOS_ATOMIC)
321 * @throws MWException
323 final public function batchPush( array $jobs, $flags = 0 ) {
324 $this->assertNotReadOnly();
326 if ( $jobs === [] ) {
327 return; // nothing to do
330 foreach ( $jobs as $job ) {
331 if ( $job->getType() !== $this->type
) {
332 throw new MWException(
333 "Got '{$job->getType()}' job; expected a '{$this->type}' job." );
334 } elseif ( $job->getReleaseTimestamp() && !$this->supportsDelayedJobs() ) {
335 throw new MWException(
336 "Got delayed '{$job->getType()}' job; delays are not supported." );
340 $this->doBatchPush( $jobs, $flags );
341 $this->aggr
->notifyQueueNonEmpty( $this->domain
, $this->type
);
343 foreach ( $jobs as $job ) {
344 if ( $job->isRootJob() ) {
345 $this->deduplicateRootJob( $job );
351 * @see JobQueue::batchPush()
352 * @param IJobSpecification[] $jobs
355 abstract protected function doBatchPush( array $jobs, $flags );
358 * Pop a job off of the queue.
359 * This requires $wgJobClasses to be set for the given job type.
360 * Outside callers should use JobQueueGroup::pop() instead of this function.
362 * @throws MWException
363 * @return Job|bool Returns false if there are no jobs
365 final public function pop() {
366 global $wgJobClasses;
368 $this->assertNotReadOnly();
369 if ( !WikiMap
::isCurrentWikiDbDomain( $this->domain
) ) {
370 throw new MWException(
371 "Cannot pop '{$this->type}' job off foreign '{$this->domain}' wiki queue." );
372 } elseif ( !isset( $wgJobClasses[$this->type
] ) ) {
373 // Do not pop jobs if there is no class for the queue type
374 throw new MWException( "Unrecognized job type '{$this->type}'." );
377 $job = $this->doPop();
380 $this->aggr
->notifyQueueEmpty( $this->domain
, $this->type
);
383 // Flag this job as an old duplicate based on its "root" job...
385 if ( $job && $this->isRootJobOldDuplicate( $job ) ) {
386 self
::incrStats( 'dupe_pops', $this->type
);
387 $job = DuplicateJob
::newFromJob( $job ); // convert to a no-op
389 } catch ( Exception
$e ) {
390 // don't lose jobs over this
397 * @see JobQueue::pop()
400 abstract protected function doPop();
403 * Acknowledge that a job was completed.
405 * This does nothing for certain queue classes or if "claimTTL" is not set.
406 * Outside callers should use JobQueueGroup::ack() instead of this function.
410 * @throws MWException
412 final public function ack( Job
$job ) {
413 $this->assertNotReadOnly();
414 if ( $job->getType() !== $this->type
) {
415 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
418 $this->doAck( $job );
422 * @see JobQueue::ack()
425 abstract protected function doAck( Job
$job );
428 * Register the "root job" of a given job into the queue for de-duplication.
429 * This should only be called right *after* all the new jobs have been inserted.
430 * This is used to turn older, duplicate, job entries into no-ops. The root job
431 * information will remain in the registry until it simply falls out of cache.
433 * This requires that $job has two special fields in the "params" array:
434 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
435 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
437 * A "root job" is a conceptual job that consist of potentially many smaller jobs
438 * that are actually inserted into the queue. For example, "refreshLinks" jobs are
439 * spawned when a template is edited. One can think of the task as "update links
440 * of pages that use template X" and an instance of that task as a "root job".
441 * However, what actually goes into the queue are range and leaf job subtypes.
442 * Since these jobs include things like page ID ranges and DB master positions,
443 * and can morph into smaller jobs recursively, simple duplicate detection
444 * for individual jobs being identical (like that of job_sha1) is not useful.
446 * In the case of "refreshLinks", if these jobs are still in the queue when the template
447 * is edited again, we want all of these old refreshLinks jobs for that template to become
448 * no-ops. This can greatly reduce server load, since refreshLinks jobs involves parsing.
449 * Essentially, the new batch of jobs belong to a new "root job" and the older ones to a
450 * previous "root job" for the same task of "update links of pages that use template X".
452 * This does nothing for certain queue classes.
454 * @param IJobSpecification $job
455 * @throws MWException
458 final public function deduplicateRootJob( IJobSpecification
$job ) {
459 $this->assertNotReadOnly();
460 if ( $job->getType() !== $this->type
) {
461 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
464 return $this->doDeduplicateRootJob( $job );
468 * @see JobQueue::deduplicateRootJob()
469 * @param IJobSpecification $job
470 * @throws MWException
473 protected function doDeduplicateRootJob( IJobSpecification
$job ) {
474 if ( !$job->hasRootJobParams() ) {
475 throw new MWException( "Cannot register root job; missing parameters." );
477 $params = $job->getRootJobParams();
479 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
480 // Callers should call JobQueueGroup::push() before this method so that if the insert
481 // fails, the de-duplication registration will be aborted. Since the insert is
482 // deferred till "transaction idle", do the same here, so that the ordering is
483 // maintained. Having only the de-duplication registration succeed would cause
484 // jobs to become no-ops without any actual jobs that made them redundant.
485 $timestamp = $this->dupCache
->get( $key ); // current last timestamp of this job
486 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
487 return true; // a newer version of this root job was enqueued
490 // Update the timestamp of the last root job started at the location...
491 return $this->dupCache
->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
495 * Check if the "root" job of a given job has been superseded by a newer one
498 * @throws MWException
501 final protected function isRootJobOldDuplicate( Job
$job ) {
502 if ( $job->getType() !== $this->type
) {
503 throw new MWException( "Got '{$job->getType()}' job; expected '{$this->type}'." );
505 $isDuplicate = $this->doIsRootJobOldDuplicate( $job );
511 * @see JobQueue::isRootJobOldDuplicate()
515 protected function doIsRootJobOldDuplicate( Job
$job ) {
516 if ( !$job->hasRootJobParams() ) {
517 return false; // job has no de-deplication info
519 $params = $job->getRootJobParams();
521 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
522 // Get the last time this root job was enqueued
523 $timestamp = $this->dupCache
->get( $key );
525 // Check if a new root job was started at the location after this one's...
526 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
530 * @param string $signature Hash identifier of the root job
533 protected function getRootJobCacheKey( $signature ) {
534 return $this->dupCache
->makeGlobalKey(
544 * Deleted all unclaimed and delayed jobs from the queue
546 * @throws JobQueueError
550 final public function delete() {
551 $this->assertNotReadOnly();
557 * @see JobQueue::delete()
558 * @throws MWException
560 protected function doDelete() {
561 throw new MWException( "This method is not implemented." );
565 * Wait for any replica DBs or backup servers to catch up.
567 * This does nothing for certain queue classes.
570 * @throws JobQueueError
572 final public function waitForBackups() {
573 $this->doWaitForBackups();
577 * @see JobQueue::waitForBackups()
580 protected function doWaitForBackups() {
584 * Clear any process and persistent caches
588 final public function flushCaches() {
589 $this->doFlushCaches();
593 * @see JobQueue::flushCaches()
596 protected function doFlushCaches() {
600 * Get an iterator to traverse over all available jobs in this queue.
601 * This does not include jobs that are currently acquired or delayed.
602 * Note: results may be stale if the queue is concurrently modified.
605 * @throws JobQueueError
607 abstract public function getAllQueuedJobs();
610 * Get an iterator to traverse over all delayed jobs in this queue.
611 * Note: results may be stale if the queue is concurrently modified.
614 * @throws JobQueueError
617 public function getAllDelayedJobs() {
618 return new ArrayIterator( [] ); // not implemented
622 * Get an iterator to traverse over all claimed jobs in this queue
624 * Callers should be quick to iterator over it or few results
625 * will be returned due to jobs being acknowledged and deleted
628 * @throws JobQueueError
631 public function getAllAcquiredJobs() {
632 return new ArrayIterator( [] ); // not implemented
636 * Get an iterator to traverse over all abandoned jobs in this queue
639 * @throws JobQueueError
642 public function getAllAbandonedJobs() {
643 return new ArrayIterator( [] ); // not implemented
647 * Do not use this function outside of JobQueue/JobQueueGroup
652 public function getCoalesceLocationInternal() {
657 * Check whether each of the given queues are empty.
658 * This is used for batching checks for queues stored at the same place.
660 * @param array $types List of queues types
661 * @return array|null (list of non-empty queue types) or null if unsupported
662 * @throws MWException
665 final public function getSiblingQueuesWithJobs( array $types ) {
666 return $this->doGetSiblingQueuesWithJobs( $types );
670 * @see JobQueue::getSiblingQueuesWithJobs()
671 * @param array $types List of queues types
672 * @return array|null (list of queue types) or null if unsupported
674 protected function doGetSiblingQueuesWithJobs( array $types ) {
675 return null; // not supported
679 * Check the size of each of the given queues.
680 * For queues not served by the same store as this one, 0 is returned.
681 * This is used for batching checks for queues stored at the same place.
683 * @param array $types List of queues types
684 * @return array|null (job type => whether queue is empty) or null if unsupported
685 * @throws MWException
688 final public function getSiblingQueueSizes( array $types ) {
689 return $this->doGetSiblingQueueSizes( $types );
693 * @see JobQueue::getSiblingQueuesSize()
694 * @param array $types List of queues types
695 * @return array|null (list of queue types) or null if unsupported
697 protected function doGetSiblingQueueSizes( array $types ) {
698 return null; // not supported
702 * @throws JobQueueReadOnlyError
704 protected function assertNotReadOnly() {
705 if ( $this->readOnlyReason
!== false ) {
706 throw new JobQueueReadOnlyError( "Job queue is read-only: {$this->readOnlyReason}" );
711 * Call wfIncrStats() for the queue overall and for the queue type
713 * @param string $key Event type
714 * @param string $type Job type
718 public static function incrStats( $key, $type, $delta = 1 ) {
721 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
723 $stats->updateCount( "jobqueue.{$key}.all", $delta );
724 $stats->updateCount( "jobqueue.{$key}.{$type}", $delta );